package com.example.illuminator.controller.User;

import Tools.Encryption.JWTEncryption;
import Tools.Exception.illuminatorStatus;
import com.example.illuminator.bean.User;
import com.example.illuminator.config.Result;
import com.example.illuminator.service.UserService;
import com.example.illuminator.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String username = user.getUsername();
        String password = user.getPassword();
        User temp = userService.getUserByUserName(username);
        if(temp==null){
            return Result.error(illuminatorStatus.LoginInvaildUser);
        }
        else if(!temp.getPassword().equals(password)){
            return Result.error(illuminatorStatus.LoginPasswordError);
        }
        else{
            Map<String,String> payload = new HashMap<>();
            payload.put("username",username);
            String token = JWTEncryption.Encrypte(payload);
            Map<String,Object> data = new HashMap<>();
            data.put("token",token);
            data.put("User",user);
            return Result.success(data);
        }
    }

    @GetMapping("/userInfo")
    public Result getUserInfo(@RequestHeader String token){
        String username = JWTEncryption.getTokenValue(token,"username").asString();
        User temp = userService.getUserByUserName(username);
        if(temp==null){
            return Result.error(illuminatorStatus.LoginInvaildUser);
        }
        return Result.success(temp);
    }

    @GetMapping("/test")
    public Result test(HttpServletRequest request){
        System.out.println(request.getHeader("token"));
        String url = request.getParameter("url");
        return Result.success();
    }
}
